<template>
  <div class="managesee">
    <div v-if="isShow">
      <TopFilter :list="topFilterList" :cols="3" :collapse="false" @filterChange="changeHandle" @onCollapse="collapseHandle"></TopFilter>
      <!-- :fetchapi="fetchApi"
        :datakey="'rows'" -->

      <FilterTable
        ref="table"
        :columns="columns"
        columnsRef="part_report_statisticalCost_orderStatistics"
        :params="fetchParams"
        :dataSource="dataList"
        :isSelectColumn="false"
        :onColumnsChange="columns => (this.columns = columns)"
        :isExportExcel="true"
        :isMemoryPagination="true"
        :onCalcExportData="exportFun"
        exportFileName="配件统计成本-按对应单统计.xlsx"
      >
      </FilterTable>
    </div>
    <!-- 详情 -->
    <!-- <div class="manageSeeInfo" v-else></div> -->
    <!-- 配件选择弹窗 -->
    <!-- <BaseDialog :visible.sync="partSelectVisible" title="选择配件" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <partSelect mode="single" :fetchapi="partSelectFetchApi" @close="partSelectVisible = false" @onConfirm="handleDetailSelectConfirm" />
    </BaseDialog> -->
    <!-- 委托书弹窗 -->
    <BaseDialog :visible.sync="partEntrustSelectVisible" title="选择委托书" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <entrustOrder mode="single" :fetchapi="partEntrustSelectFetchApi" @close="partEntrustSelectVisible = false" @onConfirm="handleEntrustSelectConfirm" />
    </BaseDialog>
    <!-- 销售单弹窗 -->
    <BaseDialog :visible.sync="partSaleSelectVisible" title="选择销售单" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <saleOrder mode="single" :fetchapi="partSaleSelectFetchApi" @close="partSaleSelectVisible = false" @onConfirm="handleSaleSelectConfirm" />
    </BaseDialog>

    <!-- 装饰单弹窗 -->
    <BaseDialog :visible.sync="partDecorateSelectVisible" title="选择装饰单" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <decorateOrder mode="single" :fetchapi="partDecorateSelectFetchApi" @close="partDecorateSelectVisible = false" @onConfirm="handleDecorateSelectConfirm" />
    </BaseDialog>
  </div>
</template>

<script>
import { getManageseeData, updateStatus, notification } from '@/api/common/notice/noticemanage/managesee/';
import { dictionary } from '@/utils/dictMixin';
import { formatDates, formatDat } from '@/utils/validate';
// import PartSelect from '@/pages/part/partPurchase/purchaseOrder/partSelect';
import entrustOrder from '@/pages/part/report/statisticalCost/commonPage/entrustOrder';
import saleOrder from '@/pages/part/report/statisticalCost/commonPage/saleOrder';
import decorateOrder from '@/pages/part/report/statisticalCost/commonPage/decorateOrder';
import { getStroageList } from '@/api/part/partOutbound/partBreak';
import { queryPartListByOrderType } from '@/api/part/partPurchase/purchaseOrder';
import { getStatisticalList, getRepairOrderList, getSalesList, getDecorationList } from '@/api/part/report/statisticalCost';
import moment from 'moment';
export default {
  name: 'managesee',
  components: {
    entrustOrder,
    saleOrder,
    decorateOrder
  },
  mixins: [dictionary],
  data() {
    return {
      isShow: true,
      topFilterList: this.createTopFilters(),
      fetchParams: { xhrAbort: true },
      visible: false,
      dialogTitle: '',
      dataList: [],
      fetchApi: getStatisticalList,
      columns: this.createTableColumns(),
      handleType: '',
      formData: {},
      urgencyData: ['ALL', 'UNDER_REPAIR', 'UNFINISHED', 'ARREARS', 'SETTLE'], // 全部、在修等复选框对应的列表值
      dataType: '',
      partSelectFetchApi: queryPartListByOrderType,
      partEntrustSelectFetchApi: getRepairOrderList,
      partSaleSelectFetchApi: getSalesList,
      partDecorateSelectFetchApi: getDecorationList,
      // partSelectVisible: false, // 是否显示配件选择弹窗
      partEntrustSelectVisible: false, // 是否显示委托单选择弹窗
      partSaleSelectVisible: false, // 是否显示销售单选择窗口
      partDecorateSelectVisible: false, // 是否显示装饰单选择窗口
      orgName: ''
    };
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
    // this.getCookie();
  },
  created() {
    this.getStorage();
  },
  methods: {
    exportFun(row) {
      for (const key in row) {
        switch (key) {
          case 'SEND_TIME':
            if (row[key]) {
              row[key] = moment(row[key]).format('YYYY-MM-DD');
            }
            break;
          case 'SPREAD':
          case 'BUY_IN_AMOUNT':
          case 'OUT_AMOUNT':
            if (row[key]) {
              row[key] = Number(row[key]).toFixed(2);
            }
            break;
          default:
            break;
        }
      }
    },
    checkBoxHandle(val) {
      console.log(val);
      console.log(val.length);
      // 长度小于初始值，代表当前有未勾选的项目
      if (this.urgencyData.length > val.length) {
        // 如果最后一个值是全部
        if (val[val.length - 1] == 'ALL') {
          this.topFilterList.find(item => item.fieldName == 'RO_STATUS').initialValue = this.urgencyData;
        }

        // 子项全中
        if (this.urgencyData.length - val.length == 1) {
          var checkAllflag = 'false';
          for (var i = 0; i < val.length; i++) {
            if (val[i] == 'ALL') {
              checkAllflag = 'true';
              val.splice(i, 1);
            }
          }
          // 如果两数组长度相差1，且只有全选未选中，则将所有值默认全选
          if (checkAllflag == 'false') {
            this.topFilterList.find(item => item.fieldName == 'RO_STATUS').initialValue = this.urgencyData;
          }
        }
      }

      console.log(val);
    },
    selectHandle(val) {
      // 选择不同的单据类型，展示不同的条件，并且调整单据弹出框
      if (val == 'REPAIR_ORDER') {
        this.topFilterList.find(item => item.fieldName == 'RO_STATUS').itemList = [
          { text: '全部', value: 'ALL' },
          { text: '在修', value: 'UNDER_REPAIR' },
          { text: '完工未结', value: 'UNFINISHED' },
          { text: '欠账', value: 'ARREARS' },
          { text: '结清', value: 'SETTLE' }
        ];
        this.topFilterList.find(item => item.fieldName == 'RO_STATUS').initialValue = ['ALL', 'UNDER_REPAIR', 'UNFINISHED', 'ARREARS', 'SETTLE'];
        this.urgencyData = ['ALL', 'UNDER_REPAIR', 'UNFINISHED', 'ARREARS', 'SETTLE'];

        this.topFilterList.find(item => item.fieldName == 'RO_NO').unitRender = () => {
          return <el-button slot="append" icon="el-icon-search" onClick={this.handleEntrustSelecterClick}></el-button>;
        };
      }
      if (val == 'SALES') {
        this.topFilterList.find(item => item.fieldName == 'RO_STATUS').itemList = [
          { text: '全部', value: 'ALL' },
          { text: '欠账', value: 'ARREARS' },
          { text: '结清', value: 'SETTLE' }
        ];
        this.topFilterList.find(item => item.fieldName == 'RO_STATUS').initialValue = ['ALL', 'ARREARS', 'SETTLE'];
        this.urgencyData = ['ALL', 'ARREARS', 'SETTLE'];
        this.topFilterList.find(item => item.fieldName == 'RO_NO').unitRender = () => {
          return <el-button slot="append" icon="el-icon-search" onClick={this.handleSaleSelecterClick}></el-button>;
        };
      }
      if (val == 'DECORATION') {
        this.topFilterList.find(item => item.fieldName == 'RO_STATUS').itemList = [
          { text: '全部', value: 'ALL' },
          { text: '在修', value: 'UNDER_REPAIR' },
          { text: '完工未结', value: 'UNFINISHED' },
          { text: '欠账', value: 'ARREARS' },
          { text: '结清', value: 'SETTLE' }
        ];
        this.topFilterList.find(item => item.fieldName == 'RO_STATUS').initialValue = ['ALL', 'UNDER_REPAIR', 'UNFINISHED', 'ARREARS', 'SETTLE'];
        this.urgencyData = ['ALL', 'UNDER_REPAIR', 'UNFINISHED', 'ARREARS', 'SETTLE'];
        this.topFilterList.find(item => item.fieldName == 'RO_NO').unitRender = () => {
          return <el-button slot="append" icon="el-icon-search" onClick={this.handleDecorateSelecterClick}></el-button>;
        };
      }
    },
    createTopFilters() {
      return [
        {
          type: 'SELECT',
          label: '仓库',
          fieldName: 'STORAGE_CODE',
          initialValue: '',
          itemList: []
        },
        {
          type: 'SELECT',
          label: '类别',
          fieldName: 'TABLE',
          initialValue: 'REPAIR_ORDER',
          clearable: false,
          itemList: [
            { text: '委托书信息', value: 'REPAIR_ORDER' },
            { text: '销售单信息', value: 'SALES' },
            { text: '装饰单信息', value: 'DECORATION' }
          ],
          // unitRender: props => {
          //   return <el-button icon="el-icon-search" onClick={() => this.selectHandle(props)}></el-button>;
          // }
          change: this.selectHandle
        },
        {
          type: 'INPUT',
          label: '单号',
          fieldName: 'RO_NO',
          placeholder: '请选择',
          unitRender: () => {
            return <el-button slot="append" icon="el-icon-search" onClick={this.handleEntrustSelecterClick}></el-button>;
          },
          readonly: true
        },
        // {
        //   type: 'INPUT',
        //   label: '配件代码',
        //   fieldName: 'partNo',
        //   placeholder: '请选择',
        //   unitRender: () => {
        //     return <el-button slot="append" icon="el-icon-search" onClick={this.handlePartSelecterClick}></el-button>;
        //   },
        //   readonly: true
        // },

        {
          type: 'RANGE_DATE',
          label: '出库日期',
          fieldName: 'SEND_TIME_START|SEND_TIME_END',
          placeholder: '请输入...',
          initialValue: [moment(new Date()).format('YYYY-MM') + '-01 00:00:00', moment(new Date()).format('YYYY-MM-DD') + ' 23:59:59'],
          rules: [{ required: true, message: '选择日期', trigger: 'blur' }]
        },

        {
          type: 'MULTIPLE_CHECKBOX',
          fieldName: 'RO_STATUS',
          initialValue: ['ALL', 'UNDER_REPAIR', 'UNFINISHED', 'ARREARS', 'SETTLE'],
          itemList: [
            { text: '全部', value: 'ALL' },
            { text: '在修', value: 'UNDER_REPAIR' },
            { text: '完工未结', value: 'UNFINISHED' },
            { text: '欠账', value: 'ARREARS' },
            { text: '结清', value: 'SETTLE' }
          ],
          change: this.checkBoxHandle
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '单据编号',
          dataIndex: 'RO_NO',
          sorter: true,
          filter: true,
          showOverflowTooltip: true,
          filterType: 'input'
        },
        {
          title: '客户代码',
          dataIndex: 'CUSTOMER_CODE',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '客户名称',
          dataIndex: 'CUSTOMER_NAME',
          sorter: true,
          filter: true,
          filterType: 'input'
        },

        {
          title: '入库金额',
          dataIndex: 'BUY_IN_AMOUNT',
          sorter: true,
          filter: true,
          summation: true,
          filterType: 'number',
          precision: 2
        },
        {
          title: '出库金额',
          dataIndex: 'OUT_AMOUNT',
          sorter: true,
          filter: true,
          summation: true,
          filterType: 'number',
          precision: 2
        },
        {
          title: '差额',
          dataIndex: 'SPREAD',
          sorter: true,
          filter: true,
          summation: true,
          filterType: 'number',
          precision: 2
        },
        {
          title: '仓库代码',
          dataIndex: 'STORAGE_CODE',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '仓库名称',
          dataIndex: 'STORAGE_NAME',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '结算状态',
          dataIndex: 'ARR_BALANCE',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: [
            { title: '未结算', value: '未结算' },
            { title: '已结算', value: '已结算' }
          ]
        },
        {
          title: '审核标识',
          dataIndex: 'PAY_OFF',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: [
            { title: '未审核', value: '未审核' },
            { title: '已审核', value: '已审核' }
          ]
        },
        {
          title: '对应单号',
          dataIndex: 'SERVICE_ADVISOR_ASS',
          sorter: true,
          filter: true,
          filterType: 'input'
        }
        // {
        //   title: '公告来源',
        //   dataIndex: 'dataType',
        //   hidden: false,
        //   sorter: true,
        //   width: 140,
        //   // filter: true,
        //   filterType: 'checkbox',
        //   filterItems: this.createDictList('1046'),
        //   render: props => {
        //     return <span>{this.createDictText(props.row.dataType, '1046')}</span>;
        //   }
        // },
        // {
        //   title: '阅读状态',
        //   dataIndex: 'readStatus',
        //   sorter: true,
        //   // filter: true,
        //   width: 100,
        //   filterType: 'input',
        //   render: props => {
        //     return <span>{props.row.readStatus == 0 ? '未读' : '已读'}</span>;
        //   }
        // }
        /* {
          title: '公告时间',
          dataIndex: 'msgNoticeTime',
          sorter: true,
          width: 150,
          //filter: true,
          filterType: 'input'
        },
        {
          title: '内容',
          dataIndex: 'msgContent',
          sorter: true,
          //filter: true,
          filterType: 'input'
        },
        {
          title: '确认状态',
          dataIndex: 'noticeConfirm1',
          sorter: true,
          width: 100,
          //filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('7042'),
          render: props => {
            return <span>{this.createDictText(props.row.noticeConfirm1, '7042')}</span>;
          }
        },*/
      ];
    },
    async getStorage() {
      const res = await getStroageList();
      this.topFilterList.find(item => item.fieldName === 'STORAGE_CODE').itemList = res.data.map(x => ({ text: x.STORAGE_NAME, value: x.STORAGE_CODE }));
    },
    async getStatistical(data) {
      console.log(data);
      let res = await getStatisticalList(data);
      if (res.resultCode == 200) {
        this.dataList = res.data.rows;
      }

      console.log(res);
    },
    getCookie() {
      let allCookie = document.cookie.split(';');
      allCookie.forEach(x => {
        if (x.indexOf('dataType') > -1) {
          this.dataType = x.split('=')[1];
        }
      });
      // 判断是否为厂端
      if (this.dataType != 10461001) {
        this.columns[4].hidden = true;
      } else {
        this.columns[4].hidden = false;
      }
    },
    // 点击配件搜索按钮
    handlePartSelecterClick() {
      this.partSelectVisible = true;
    },
    // 配件选择点击确定
    handleDetailSelectConfirm(e) {
      // this.formList.find(item => item.fieldName == 'partName').initialValue = e[0].partName;
      this.topFilterList.find(item => item.fieldName == 'partNo').initialValue = e[0].partNo;
    },

    // 点击委托单搜索按钮
    handleEntrustSelecterClick() {
      this.partEntrustSelectVisible = true;
    },
    // 委托单选择点击确定
    handleEntrustSelectConfirm(e) {
      // this.formList.find(item => item.fieldName == 'partName').initialValue = e[0].partName;
      this.topFilterList.find(item => item.fieldName == 'RO_NO').initialValue = e[0].RO_NO;
    },
    // 点击销售单搜索按钮
    handleSaleSelecterClick() {
      this.partSaleSelectVisible = true;
    },
    // 销售单选择点击确定
    handleSaleSelectConfirm(e) {
      // this.formList.find(item => item.fieldName == 'partName').initialValue = e[0].partName;
      this.topFilterList.find(item => item.fieldName == 'RO_NO').initialValue = e[0].SALES_PART_NO;
    },
    // 点击装饰单搜索按钮
    handleDecorateSelecterClick() {
      this.partDecorateSelectVisible = true;
    },
    // 装饰单选择点击确定
    handleDecorateSelectConfirm(e) {
      // this.formList.find(item => item.fieldName == 'partName').initialValue = e[0].partName;
      this.topFilterList.find(item => item.fieldName == 'RO_NO').initialValue = e[0].BILL_NO;
    },
    // showHandler() {
    //   this.dialogTitle = `${this.conf[this.handleType]}`;
    //   this.visible = true;
    // },
    // 搜索
    async changeHandle(val) {
      // 将标签属性放到对象当中
      val.LABEL = 'GROUP_STOCK';
      val.SEND_TIME_START = val.SEND_TIME_START ? val.SEND_TIME_START.split(' ')[0] + ' 00:00:00' : '';
      val.SEND_TIME_END = val.SEND_TIME_END ? val.SEND_TIME_END.split(' ')[0] + ' 23:59:59' : '';
      // 增加时间限制
      if (val.SEND_TIME_START || val.SEND_TIME_END) {
        let diffMonth = moment(val.SEND_TIME_END).diff(moment(val.SEND_TIME_START), 'months');
        if (diffMonth > 5) return this.$notify.warning({ title: '提示信息', message: '起止日期跨度不能超过半年' });
      }
      // this.getStatistical(val);
      // this.fetchParams = Object.assign({}, val);
      // this.columns = [...this.columns];
      // this.fetchParams = Object.assign({ sort: 'wayId', order: 'desc' }, val);
      this.$refs.table.START_LOADING();
      let res = await this.fetchApi(val);
      this.$refs.table.STOP_LOADING();
      if (res.resultCode == 200) {
        this.dataList = res.data;
      }
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },

    // 返回
    closeHandler() {
      this.isShow = true;
    }
    /*
    closeHandler(val, type) {
      this.visible = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    } */
  }
};
</script>

<style lang="less" scoped>
/* .manageSeeInfo{
  height: 100%;
  position: relative;
  padding-left: 40px;
  font-size: 16px;
  h3{
    text-align: center;
    font-size: 25px;
    font-weight: 900;
    color: #666;
    line-height: 60px;
  }
  p{
    margin-bottom: 30px;
    span{
      margin-right: 40px;
    }
  }
  .manageSeeInfoCont{
    margin-bottom: 85px;
  }
  .manageSeeInfoBtn{

    text-align: center;
  }
} */
</style>
